package Shangji3.JDK;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LoggingJdkProxy implements InvocationHandler {
    private final Object target;

    public LoggingJdkProxy(Object target) {
        this.target = target;
    }

    /**
     * 创建代理对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T createProxy(T target) {
        return (T) Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new LoggingJdkProxy(target)
        );
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 方法执行前记录日志
        String methodName = method.getName();
        String className = target.getClass().getSimpleName();
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));

        System.out.println("【JDK代理-前置日志】时间: " + timestamp +
                " | 类: " + className +
                " | 方法: " + methodName +
                " | 参数: " + (args != null ? java.util.Arrays.toString(args) : "无"));

        long startTime = System.currentTimeMillis();

        try {
            // 执行原始方法
            Object result = method.invoke(target, args);
            long endTime = System.currentTimeMillis();

            // 方法执行后记录日志
            timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
            System.out.println("【JDK代理-后置日志】时间: " + timestamp +
                    " | 类: " + className +
                    " | 方法: " + methodName +
                    " | 执行时间: " + (endTime - startTime) + "ms" +
                    " | 结果: " + (result != null ? result.toString() : "void"));

            return result;

        } catch (Exception e) {
            // 方法执行异常记录日志
            String errorTimestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
            System.out.println("【JDK代理-异常日志】时间: " + errorTimestamp +
                    " | 类: " + className +
                    " | 方法: " + methodName +
                    " | 异常: " + e.getCause().getMessage());
            throw e.getCause();
        }
    }
}
